package sdk.org.apache.lucene.D01_Hello;

import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.StandardDirectoryReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;

public class Search {

    /**
     * 根据关键字检索文件
     * 
     * @param indexDir
     *            存放索引的目录
     * @param key
     *            关键字
     * @throws IOException
     * @throws ParseException 
     */
    public static void search(String indexDir, String key) throws IOException, ParseException {
        Directory directory = new SimpleFSDirectory(Paths.get(indexDir));
        IndexReader reader = DirectoryReader.open(directory);

        Analyzer analyzer=new StandardAnalyzer();
        QueryParser queryParser=new QueryParser("fileContents", analyzer);
        Query query=queryParser.parse(key);
        
        
        IndexSearcher searcher = new IndexSearcher(reader);

        long startTime = System.currentTimeMillis();
        TopDocs topDocs=searcher.search(query, 10);
        long endTime=System.currentTimeMillis();
        System.out.println("匹配    "+key+"   总共花费："+(endTime-startTime)+"毫秒，查询到"+topDocs.totalHits+"条记录");
        
        for(ScoreDoc scoreDoc:topDocs.scoreDocs) {
            Document document=searcher.doc(scoreDoc.doc);
            System.out.println(document.get("filePath"));
        }
        
    }
    
    
    public static void main(String[] args) {
        String indexDir="E:\\Temp\\lucene\\index";
        String key="aaaaa";  // Zygmunt#Saloni
        try {
            Search.search(indexDir, key);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}